﻿package src.utils
{
	import com.debug.nl.demonsters.debugger.MonsterDebugger;
	import flash.events.*;
	import flash.xml.*;
	import flash.net.*;
	
	public class StringImport extends EventDispatcher {

		private var obj:Object;
		private var loader:URLLoader;
		private var config:Object;
		private var status:Number;
		public var xml:XML=new XML  ;

		public function StringImport(obj:Object) 
		{		
			config=obj;
			loader=new URLLoader  ;
			loader.addEventListener(Event.COMPLETE,onLoadedXML);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,errorHandler);
			loader.addEventListener(IOErrorEvent.IO_ERROR,errorHandler);
			loader.addEventListener(HTTPStatusEvent.HTTP_STATUS,statusHandler);
		}
		
		public function load(type:String):void 
		{		
			var language:String = type;
			var file:String;
			try {
				if (config.resources == '')
				{
					file = config.resources + 'language/string_' + language + '.xml';
				}
				else
				{
					file = config.resources + '/swf/language/string_' + language + '.xml';
				}
				
					loader.load(new URLRequest(file));
					
					MonsterDebugger.trace(this, 'STRING import: ' + file)
					
					
			} catch (e:Error) {
				trace("error StringImport");
			}
		}
		
		public function onLoadedXML(e:Event):void 
		{		
			trace("#languagelist LOADED test!!");
			try {
				var dat = XML(e.target.data);
				
			} catch (err:Error) {
				var str=status + ': This playlist is not a valid XML file.';
					dispatchEvent(new ErrorEvent(ErrorEvent.ERROR, false, false, str));
					trace("error on data");
				return;
			}
			var fmt = dat.localName().toLowerCase();	
			trace("fmt : " + fmt );
			if (fmt == 'file') {
				obj = new Object();
				for each (var i in dat.children()) {
					obj[i.localName()] = i.text().toString();
					
				}
			
		
			} else {
				fmt='Unknown playlist format: ' + fmt;
				dispatchEvent(new ErrorEvent(ErrorEvent.ERROR,false,false,fmt));
				return;
			}
			
				dispatchEvent(new Event(Event.COMPLETE));
				trace('LANGUAGE COMPLETE');
		
		}


		private function statusHandler(evt:HTTPStatusEvent) {
			status=evt.status;
		}
	
		private function errorHandler(evt:ErrorEvent) {
			dispatchEvent(new ErrorEvent(ErrorEvent.ERROR,false,false,status + ': ' + evt.text));
		}

		public function get languagelist():Object {
		
			return obj;
			
		}
		
	}
}